package com.lock.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.condition
 * @ClassName:Test01
 * @Description: 多个condition实现通知部分线程
 * @Author: zhangxiaoyu
 * @date 2021/1/20 14:37
 */
public class Test01 {
    
    static  class Ser{
        
        private ReentrantLock lock = new ReentrantLock();
        
        //定义
        private Condition conditionA = lock.newCondition();
        private Condition conditionB = lock.newCondition();
        
        //定义方法来使用conditionA等待
        public void  waitMethodA(){

            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"begin wait" + System.currentTimeMillis());

                conditionA.await();
                System.out.println(Thread.currentThread().getName()+"end wait"+System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                lock.unlock();
            }

        }

        //定义方法来使用conditionB等待
        public void  waitMethodB(){

            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"begin wait" + System.currentTimeMillis());

                conditionB.await();
                System.out.println(Thread.currentThread().getName()+"end wait"+System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                lock.unlock();
            }

        }

        //定义方法 唤醒confitionA上的等待
        public  void  signalA(){
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"signal A time"+System.currentTimeMillis());
                conditionA.signal();
            } finally {
                lock.unlock();
            }
        }

        public  void  signalB(){
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"signal B time"+System.currentTimeMillis());
                conditionB.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
         Ser t = new Ser();

         //开启两个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                t.waitMethodA();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.waitMethodB();
            }
        }).start();

        //睡眠3秒
        Thread.sleep(3000);
        //唤醒
        t.signalB();
    }

}
